<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Generator {

	function generate_username($entities=null, $id=null){

		if(!$entities) return false;

		$CI =& get_instance();
		$CI->config->load('username_header');
		$header = $CI->config->item($entities);

		if($id == null){

			$query = $CI->doctrine->em->createQuery('SELECT a FROM '.$entities.' a ORDER BY a.username DESC');
			$last_akun = $query->getResult();

			$last_username = $last_akun[0]->get_username();
			$new_username = substr($last_username,strlen($header));
			settype($new_username,'integer');
			$new_username = sprintf($header.'%04d',$new_username+1);

		} else {
			$new_username = sprintf($header.'%04d',$id);
		}

		return $new_username;
	}

	function generate_int_username($entities=null, $username=null){

		if($entities == 'models\Perusahaan')
			$entities = 'models\Customer';

		$CI =& get_instance();
		$CI->config->load('username_header');
		$header = $CI->config->item($entities);

		if(!$username){
			$query = $CI->doctrine->em->createQuery('SELECT a FROM '.$entities.' a ORDER BY a.username DESC');
			$last_akun = $query->getResult();

			$last_username = $last_akun[0]->get_username();
			$new_username = substr($last_username,strlen($header));
			settype($new_username,'integer');
			$new_username++;

		}else{
			$new_username = substr($username,strlen($header));
			settype($new_username,'integer');
		}

		return $new_username;

	}

	function generate_password($length=6,$level=1){

		list($usec, $sec) = explode(' ', microtime());
		srand((float) $sec + ((float) $usec * 100000));

		$validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
		$validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		$validchars[3] = "0123456789_!@#$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%&*()-=+/";

		$password  = "";
		$counter   = 0;

		while ($counter < $length) {
			$actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);

			// All character must be different
			if (!strstr($password, $actChar)) {
				$password .= $actChar;
				$counter++;
			}
		}

		return $password;
	}

}
